<template>
    <div class="edit-popup">
        <popup ref="popupRef" title="朋友圈精准投放" :async="true" width="550px" @confirm="handleSubmit" @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="90px" :rules="formRules" @submit.prevent>
                * 请选择需要精准投送朋友圈的微信号
                <!-- <span v-if="formData.push_count !== undefined" style="color: #409EFF; font-weight: bold;">(当前投放数量/投放限制: {{ formData.push_count }}/{{ formData.push_limit }})</span> -->
                <el-form-item prop="select_type" label="录入方式" required>
                    <el-radio-group v-model="formData.select_type" @change="handleSelectTypeChange(formData.id)">
                        <el-radio :value="1">手动录入</el-radio>
                        <el-radio :value="4">选择客群库</el-radio>
                        <el-radio :value="5">外链添加</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item prop="wechat_tags" label="投放账号" v-if="formData.select_type == 1">
                    <el-tag size='large' v-for="tag in dynamicTags" :key="tag" class="mx-1" closable
                        :disable-transitions="false" @close="handleClose(tag, '1')">
                        {{ tag }}
                    </el-tag>

                    <el-input type="textarea" v-if="wechatInputVisible" ref="InputRef" class="ml-1 w-20"
                        v-model="wechatInputValue" :rows="5" style="width:400px" @blur="handleWechatInputConfirm"
                        @keyup.enter.prevent="handleWechatInputConfirm">
                        <!-- <el-input v-if="wechatInputVisible" ref="InputRef" class="ml-1 w-20"  v-model="wechatInputValue"
                        size="default" 
				
						@blur="handleWechatInputConfirm" @keyup.enter.prevent="handleWechatInputConfirm"> -->
                    </el-input>
                    <el-button v-else class="button-new-tag ml-1" size="default" @click="showWechatInput"> +
                        新增</el-button>
                </el-form-item>

                <el-form-item prop="customer_group" label="客群库" v-if="formData.select_type == 4">
                    <el-select v-model="formData.customer_group" placeholder="请选择客群库" style="width: 100%">

                        <el-option v-for="item in customerGroups" :key="item.id" :label="item.title" :value="item.id" />
                    </el-select>
                </el-form-item>


                <el-form-item label="外链地址" v-if="formData.select_type == 5 && h5_url_show">
                    <el-input ref="InputRef" class="ml-1 w-20" v-model="h5_url" size="default" style="width:300px;"
                        readonly></el-input>
                    <el-button type="primary" style="margin-left:10px" @click="copyUrl">复制</el-button>
                </el-form-item>

                <!-- 配置数量 -->
                <div class="config-stats-container">
                    <!-- <div class="config-stat-item">
                        <div class="config-stat-content">
                            <div class="config-stat-label">已授权主体数</div>
                            <div class="config-stat-value">
                                <span class="current-count">0</span>
                                <span class="separator">/</span>
                                <span class="total-count">100</span>
                            </div>
                        </div>
                    </div>

                    <div class="config-stat-item">
                        <div class="config-stat-content">
                            <div class="config-stat-label">可授权主体数</div>
                            <div class="config-stat-value">
                                <span class="current-count">0</span>
                                <span class="separator">/</span>
                                <span class="total-count">100</span>
                            </div>
                        </div>
                    </div> -->

                    <div class="config-stat-item">
                        <div class="config-stat-content">
                            <div class="config-stat-label">投放用户</div>
                            <div class="config-stat-value">
                                <span class="current-count">{{ vdata.push_limit }}</span>
                                <!-- <span class="separator">/</span>
                                <span class="total-count">{{ vdata.push_count === 0 ? '无限制' : vdata.push_count }}</span> -->
                            </div>
                        </div>
                    </div>

                    <!-- <div class="config-stat-item">
                        <div class="config-stat-content">
                            <div class="config-stat-label">可投放用户数</div>
                            <div class="config-stat-value">
                                <span class="current-count">0</span>
                                <span class="separator">/</span>
                                <span class="total-count">100</span>
                            </div>
                        </div>
                    </div> -->
                </div>

            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup name="tencentAdvertisingUserAdListEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiTencentAdvertisingUserAdListPlacement, apiTencentAdvertisingUserAdListDetail, apiTencentAdvertisingUserAdListCustomerGroups, getCount, getWechatCount } from '@/api/tencent_advertising_user_ad_list'
import { getAdGroupShareLink } from '@/api/customer-group'
import { ElLoading, ElInput } from 'element-plus'
import type { PropType } from 'vue'
import feedback from '@/utils/feedback'
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const h5_url = ref('');
const h5_url_show = ref(false)


// 表单数据
const formData = reactive({
    id: 0,
    select_type: 1,
    tag_wechats: [],
    customer_group: "", // 修改初始值为数字类型
    push_count: undefined as number | undefined,
    push_limit: undefined as number | undefined
})

const tf_data = reactive({
    val: '',
    cities: [],
    total: 0,
    pagesize: 1,
    limit: 10,
})

const vdata = reactive({
    push_count: 0,
    push_limit: 0,
})

const dynamicTags = ref<string[]>([]);
//ref([])

const wechatInputValue = ref('')
const wechatInputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()

// 客群库列表
interface CustomerGroup {
    id: number
    title: string
}

const customerGroups = ref<CustomerGroup[]>([])

// 获取客群库列表
const getCustomerGroups = async () => {
    try {
        const res = await apiTencentAdvertisingUserAdListCustomerGroups()
        console.log('getCustomerGroups', res);
        if (res.code === 1) {
            customerGroups.value = res.list;

        }
    } catch (error) {
        console.error('获取客群库列表失败:', error)
    }
}

const handleClose = (tag: string, type: string) => {
    if (type == "1") {
        dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
    }
    console.log('关闭')
    h5_url.value = '';
    h5_url_show.value = false

    // 重置录入方式为手动录入
    formData.select_type = 1
    formData.customer_group = ""
    // 清空手动录入的标签
    dynamicTags.value = []
}

const showWechatInput = () => {
    wechatInputVisible.value = true
    nextTick(() => {
        InputRef.value!.input!.focus()
    })
}

const handleSelectTypeChange = async (id: number) => {
    if (formData.select_type == 5) {

        try {
            const res = await getAdGroupShareLink(id)
            console.log('getAdGroupShareLink', res);
            if (res.code === 1) {
                h5_url.value = res.url || 'https://www.baidu.com'
                h5_url_show.value = true
            }
        } catch (error) {
            console.error('获取分享链接失败:', error)
            h5_url.value = 'https://www.baidu.com'
        }
    }
}

const copyUrl = () => {
    navigator.clipboard.writeText(h5_url.value);
    feedback.msgSuccess('复制成功');
}

const handleWechatInputConfirm = () => {
    console.log('触发确认111:', wechatInputValue.value)
    if (wechatInputValue.value) {
        // 处理包含空格或换行符的输入，拆分为多行
        const lines = wechatInputValue.value
            .split(/[\s\n]+/)  // 使用正则表达式同时匹配空格和换行符
            .map(line => line.trim())  // 去除每行前后空格
            .filter(line => line !== '')  // 过滤空行

        // 计算添加新标签后的总数量
        const currentCount = dynamicTags.value.length;
        const newCount = currentCount + lines.length;

        console.log(currentCount, newCount);

        // 限制数量为10个（可根据需要修改）
        const MAX_TAGS = 20;

        if (newCount > MAX_TAGS) {
            // 超出限制时提示用户
            //feedback.msgError(`最多只能添加${MAX_TAGS}个标签，当前已选${currentCount}个,本次最多还能添加${MAX_TAGS - currentCount}个`)
            feedback.msgError(`最多只能添加${MAX_TAGS}个微信号`)
            // 截取符合数量限制的部分
            const allowedCount = MAX_TAGS - currentCount;
            if (allowedCount > 0) {
                dynamicTags.value = [...dynamicTags.value, ...lines.slice(0, allowedCount)];
            }
        } else {
            // 未超出限制，全部添加
            dynamicTags.value = [...dynamicTags.value, ...lines];
        }

        console.log(dynamicTags.value);
    }
    wechatInputVisible.value = false
    wechatInputValue.value = ''
}

// 表单验证
const formRules = reactive<any>({
    select_type: [
        { required: true, message: '请选择录入方式', trigger: 'change' }
    ],
    customer_group: [
        { required: true, message: '请选择客群库', trigger: 'change' }
    ]

})


// 获取详情
const setFormData = async (data: Record<any, any>) => {
    // formData.value.id=data.id
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }

    let res = await getWechatCount({ id: formData.id })
    vdata.push_count = res.push_count
    vdata.push_limit = res.push_limit
    console.log(formData, '44444444444')
}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiTencentAdvertisingUserAdListDetail({
        id: row.id
    })
    setFormData(data)
}


// 提交按钮
const handleSubmit = async () => {
    // 如果是手动录入且没有添加投放账号，则提示并返回
    if (formData.select_type === 1 && dynamicTags.value.length === 0) {
        feedback.msgError('请添加投放账号')
        return
    }

    // 如果是客群库类型且未选择客群库，则提示并返回
    if (formData.select_type === 4 && !formData.customer_group) {
        feedback.msgError('请选择客群库')
        return
    }

    const loading = ElLoading.service({ lock: true, text: 'Loading...', background: 'rgba(0, 0, 0, 0.7)', })

    try {
        await formRef.value?.validate()
    } catch (error) {
        loading.close()
        return
    }

    const data = { ...formData, ...{ wechat_list: dynamicTags.value } }

    try {
        let res = await apiTencentAdvertisingUserAdListPlacement(data)
        console.log(res, 'resresresresresresresresresresresresres')
        loading.close()
        if (res.data.code == 1) {
            feedback.msgSuccess(res.data.msg)
            dynamicTags.value = []
            popupRef.value?.close()
            emit('success')
        } else {
            feedback.msgError(res.data.msg)
        }
    } catch (error) {
        loading.close()
        feedback.msgError('提交失败，请重试')
    }
}

// 打开弹窗
const open = (type = 'add') => {
    mode.value = type
    console.log(type);
    if (type === 'placement') {
        getCustomerGroups()
    }
    popupRef.value?.open()
}

const getCountData = async () => {
    const res = await getCount()
    console.log(res, 'resresresresresresresresresresresresresres')
}

getCountData()

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>

<style scoped>
/* 配置统计样式 */
.config-stats-container {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    margin-left: 16px;
    align-items: center;
}

.config-stat-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 6px 12px;
    background: #f8fafc;
    border: 1px solid #e5e7eb;
    border-radius: 6px;
    transition: all 0.3s ease;
    min-width: 140px;
    height: 32px;
}

.config-stat-item:hover {
    background: #f1f5f9;
    border-color: #3b82f6;
}

.config-stat-icon {
    width: 40px;
    height: 40px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    color: white;
    background: linear-gradient(135deg, #10b981, #34d399);
    box-shadow: 0 3px 10px rgba(16, 185, 129, 0.3);
    flex-shrink: 0;
}

.config-stat-icon.available {
    background: linear-gradient(135deg, #3b82f6, #60a5fa);
    box-shadow: 0 3px 10px rgba(59, 130, 246, 0.3);
}

.config-stat-content {
    flex: 1;
    min-width: 0;
    display: flex;
    align-items: center;
    gap: 8px;
}

.config-stat-label {
    font-size: 12px;
    color: #6b7280;
    font-weight: 500;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.config-stat-value {
    display: flex;
    align-items: center;
    gap: 2px;
    font-size: 14px;
    font-weight: 600;
    color: #1f2937;
}

.current-count {
    color: #10b981;
}

.separator {
    color: #9ca3af;
    font-weight: 500;
}

.total-count {
    color: #6b7280;
    font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .config-stats-container {
        flex-direction: column;
        gap: 12px;
        margin-left: 0;
        margin-top: 12px;
    }

    .config-stat-item {
        min-width: auto;
        width: 100%;
    }
}
</style>